from flask import Blueprint, render_template, request, jsonify,g
from exts import db
from fun import hash_password
from models import DAdmin as Dtable
admin_admin = Blueprint('admin',__name__,url_prefix='/admin')

@admin_admin.route('/index')
def index():
    where=[]
    page = int(request.args.get('page', '1'))
    key = request.args.get('key', '')
    if(key!=''):
        where.append(Dtable.name.like("%"+key+"%"))
    list = Dtable.query.filter(*where).order_by(Dtable.id.desc()).paginate(page=page, per_page=g.config['PAGE_NUM'])

    data={
        'keys':{'key':key},
        'data':list
    }
    return render_template('admin/admin/index.html',**data)

@admin_admin.route('/add')
def add():
    return render_template('admin/admin/edit.html',info=None)

@admin_admin.route('/edit')
def edit():
    id = request.args.get('id', '0')
    info = Dtable.query.filter(Dtable.id == id).first()  # 返回模型对象/None
    return render_template('admin/admin/edit.html',info=info)

@admin_admin.route('/save',methods=['POST'])
def save():
    post = request.form.to_dict()
    print(post)
    if post['id']=='0':
        post.pop('id')
        post['pwd']=hash_password(post['pwd'])
        adddb = Dtable(**post)
        db.session.add(adddb)
        db.session.commit()
    else:
        post['pwd'] = hash_password(post['pwd'])
        Dtable.query.filter(Dtable.id == post['id']).update(post)
        db.session.commit()

    return jsonify({'code': 200, 'msg': "保存成功!"})


@admin_admin.route('/dellete')
def delete():
    id = request.args.get('id', '0')
    Dtable.query.filter(Dtable.id == id).delete()
    db.session.commit()
    return jsonify({'code': 200, 'msg': "删除成功!"})

@admin_admin.route('/status')
def status():
    id = int(request.args.get('id', 0))
    v = int(request.args.get('v', 0))
    Dtable.query.filter(Dtable.id == id).update({'status':abs(v-1)})
    db.session.commit()
    return jsonify({'code': 200, 'msg': "操作成功!"})